package com.egg.auth.service.job.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egg.auth.entity.job.Job;
import com.egg.auth.enums.job.JobAuthCodeEnum;
import com.egg.auth.mapper.job.JobMapper;
import com.egg.auth.model.request.web.JobPostOrPut;
import com.egg.auth.service.job.IJobService;
import com.egg.common.core.exception.CustomException;
import com.egg.common.mybatis.service.impl.BaseServiceImpl;
import com.egg.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.Optional;


@Slf4j
@Service
public class JobServiceImpl extends BaseServiceImpl<JobMapper, Job> implements IJobService {


    @Autowired
    private JobLinkUserServiceImpl jobLinkUserService;


    private boolean existName(String name) {
        return existName(name, Optional.empty());
    }

    private boolean existName(String name, Optional<? extends Serializable> filterId) {
        if (ObjectUtil.isEmpty(name)) {
            return false;
        }
        LambdaQueryWrapper<Job> qw = buildLambdaSortQw();
        qw.eq(Job::getName, name);
        filterId.ifPresent(o -> qw.notIn(Job::getId, o));
        return count(qw) > 0;
    }

    @Override
    public Long add(JobPostOrPut param) {
        if (JobAuthCodeEnum.isInvalid(param.getAuthCode())) {
            throw new CustomException(String.format("编码[%s]无效", param.getAuthCode()));
        }
        if (existName(param.getName())) {
            throw new CustomException(String.format("名称[%s]已存在", param.getName()));
        }
        Job job = JsonUtil.objToObj(param, Job.class);
        baseSave(job);
        return job.getId();
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void put(Serializable id, JobPostOrPut param) {
        if (JobAuthCodeEnum.isInvalid(param.getAuthCode())) {
            throw new CustomException(String.format("编码[%s]无效", param.getAuthCode()));
        }
        Job exist = baseGetById(id);
        if (existName(param.getName(), Optional.of(exist.getId()))) {
            throw new CustomException(String.format("名称[%s]已存在", param.getName()));
        }
        this.baseDel(id);
        Job job = JsonUtil.objToObj(param, Job.class);
        job.setId(exist.getId());
        baseSave(job);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void del(Collection<? extends Serializable> ids) {
        if (ObjectUtil.isEmpty(ids)) {
            return;
        }
        this.baseDel(ids);
        jobLinkUserService.delByJobId(ids);
    }


}
